//! # 网关核心配置定义
//!
//! 定义网关系统的统一配置结构，提供一致的配置管理机制。

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// 网关配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayConfig {
    /// 服务器配置
    pub server: ServerConfig,
    /// 路由配置
    pub routing: RoutingConfig,
    /// 认证配置
    pub auth: AuthConfig,
    /// 限流配置
    pub rate_limit: RateLimitConfig,
    /// 服务发现配置
    pub service_discovery: ServiceDiscoveryConfig,
    /// 负载均衡配置
    pub load_balance: LoadBalanceConfig,
    /// 中间件配置
    pub middleware: MiddlewareConfig,
    /// 监控配置
    pub monitoring: MonitoringConfig,
    /// 日志配置
    pub logging: LoggingConfig,
}

/// 服务器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// 监听地址
    pub host: String,
    /// 监听端口
    pub port: u16,
    /// 最大并发连接数
    pub max_connections: Option<u32>,
    /// 请求超时时间（秒）
    pub request_timeout: u64,
    /// 保持连接超时时间（秒）
    pub keep_alive_timeout: u64,
    /// 是否启用HTTPS
    pub enable_https: bool,
    /// TLS证书配置
    pub tls: Option<TlsConfig>,
}

/// TLS配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
    /// 证书文件路径
    pub cert_file: String,
    /// 私钥文件路径
    pub key_file: String,
    /// CA证书文件路径
    pub ca_file: Option<String>,
}

/// 路由配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingConfig {
    /// 路由规则列表
    pub routes: Vec<RouteRule>,
    /// 默认超时时间（毫秒）
    pub default_timeout: u64,
    /// 是否启用路径重写
    pub enable_path_rewrite: bool,
    /// 是否启用请求转换
    pub enable_request_transform: bool,
}

/// 路由规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteRule {
    /// 规则ID
    pub id: String,
    /// 匹配路径模式
    pub path_pattern: String,
    /// HTTP方法列表
    pub methods: Vec<String>,
    /// 目标服务名
    pub target_service: String,
    /// 路径重写规则
    pub path_rewrite: Option<String>,
    /// 请求头转换规则
    pub header_transforms: Vec<HeaderTransform>,
    /// 超时时间（毫秒）
    pub timeout: Option<u64>,
    /// 重试次数
    pub retry_count: Option<u32>,
}

/// 请求头转换规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeaderTransform {
    /// 操作类型
    pub action: HeaderAction,
    /// 请求头名称
    pub name: String,
    /// 请求头值
    pub value: Option<String>,
}

/// 请求头操作类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HeaderAction {
    /// 添加
    Add,
    /// 设置
    Set,
    /// 移除
    Remove,
}

/// 认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    /// 是否启用认证
    pub enabled: bool,
    /// 认证提供者配置
    pub providers: Vec<AuthProvider>,
    /// JWT配置
    pub jwt: Option<JwtConfig>,
    /// API密钥配置
    pub api_key: Option<ApiKeyConfig>,
    /// 基础认证配置
    pub basic_auth: Option<BasicAuthConfig>,
}

/// 认证提供者
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthProvider {
    /// 提供者名称
    pub name: String,
    /// 提供者类型
    pub provider_type: String,
    /// 配置参数
    pub config: HashMap<String, String>,
    /// 是否启用
    pub enabled: bool,
}

/// JWT配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtConfig {
    /// 密钥
    pub secret: String,
    /// 算法
    pub algorithm: String,
    /// 过期时间（秒）
    pub expiration: u64,
    /// 签发者
    pub issuer: Option<String>,
    /// 受众
    pub audience: Option<String>,
}

/// API密钥配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyConfig {
    /// 请求头名称
    pub header_name: String,
    /// 查询参数名称
    pub query_param: Option<String>,
    /// 有效密钥列表
    pub valid_keys: Vec<String>,
}

/// 基础认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BasicAuthConfig {
    /// 用户凭据
    pub credentials: HashMap<String, String>,
    /// 认证域
    pub realm: String,
}

/// 限流配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// 是否启用限流
    pub enabled: bool,
    /// 全局限流规则
    pub global: Option<RateLimitRule>,
    /// 按服务限流规则
    pub per_service: HashMap<String, RateLimitRule>,
    /// 按用户限流规则
    pub per_user: Option<RateLimitRule>,
    /// 按IP限流规则
    pub per_ip: Option<RateLimitRule>,
}

/// 限流规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitRule {
    /// 请求数限制
    pub requests: u32,
    /// 时间窗口（秒）
    pub window: u64,
    /// 突发流量限制
    pub burst: Option<u32>,
}

/// 服务发现配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceDiscoveryConfig {
    /// 服务发现类型
    pub discovery_type: String,
    /// 注册中心地址
    pub registry_urls: Vec<String>,
    /// 命名空间
    pub namespace: Option<String>,
    /// 服务刷新间隔（秒）
    pub refresh_interval: u64,
    /// 健康检查间隔（秒）
    pub health_check_interval: u64,
    /// 连接超时时间（毫秒）
    pub connection_timeout: u64,
}

/// 负载均衡配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadBalanceConfig {
    /// 负载均衡策略
    pub strategy: String,
    /// 健康检查配置
    pub health_check: HealthCheckConfig,
    /// 故障转移配置
    pub failover: FailoverConfig,
}

/// 健康检查配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckConfig {
    /// 是否启用健康检查
    pub enabled: bool,
    /// 检查路径
    pub path: String,
    /// 检查间隔（秒）
    pub interval: u64,
    /// 超时时间（毫秒）
    pub timeout: u64,
    /// 连续成功次数阈值
    pub healthy_threshold: u32,
    /// 连续失败次数阈值
    pub unhealthy_threshold: u32,
}

/// 故障转移配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailoverConfig {
    /// 是否启用故障转移
    pub enabled: bool,
    /// 最大重试次数
    pub max_retries: u32,
    /// 重试间隔（毫秒）
    pub retry_interval: u64,
    /// 断路器配置
    pub circuit_breaker: Option<CircuitBreakerConfig>,
}

/// 断路器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitBreakerConfig {
    /// 失败率阈值（百分比）
    pub failure_threshold: f64,
    /// 时间窗口（秒）
    pub time_window: u64,
    /// 最小请求数
    pub min_requests: u32,
    /// 半开状态允许的请求数
    pub half_open_max_calls: u32,
}

/// 中间件配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MiddlewareConfig {
    /// 中间件列表
    pub middlewares: Vec<MiddlewareDefinition>,
    /// 是否启用请求ID生成
    pub enable_request_id: bool,
    /// 是否启用访问日志
    pub enable_access_log: bool,
    /// 是否启用CORS
    pub enable_cors: bool,
    /// CORS配置
    pub cors: Option<CorsConfig>,
}

/// 中间件定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MiddlewareDefinition {
    /// 中间件名称
    pub name: String,
    /// 是否启用
    pub enabled: bool,
    /// 优先级
    pub priority: i32,
    /// 配置参数
    pub config: HashMap<String, String>,
}

/// CORS配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorsConfig {
    /// 允许的源
    pub allowed_origins: Vec<String>,
    /// 允许的方法
    pub allowed_methods: Vec<String>,
    /// 允许的请求头
    pub allowed_headers: Vec<String>,
    /// 暴露的响应头
    pub exposed_headers: Vec<String>,
    /// 是否允许凭据
    pub allow_credentials: bool,
    /// 预检请求缓存时间（秒）
    pub max_age: u64,
}

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// 是否启用监控
    pub enabled: bool,
    /// 指标收集间隔（秒）
    pub metrics_interval: u64,
    /// 监控端点路径
    pub metrics_path: String,
    /// 健康检查端点路径
    pub health_path: String,
    /// Prometheus配置
    pub prometheus: Option<PrometheusConfig>,
}

/// Prometheus配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrometheusConfig {
    /// 是否启用
    pub enabled: bool,
    /// 推送网关地址
    pub push_gateway: Option<String>,
    /// 作业名称
    pub job_name: String,
    /// 推送间隔（秒）
    pub push_interval: u64,
}

/// 日志配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// 日志级别
    pub level: String,
    /// 日志格式
    pub format: String,
    /// 日志输出目标
    pub output: Vec<String>,
    /// 日志文件配置
    pub file: Option<LogFileConfig>,
}

/// 日志文件配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogFileConfig {
    /// 文件路径
    pub path: String,
    /// 最大文件大小（MB）
    pub max_size: u64,
    /// 最大文件数量
    pub max_files: u32,
    /// 是否压缩归档
    pub compress: bool,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            server: ServerConfig::default(),
            routing: RoutingConfig::default(),
            auth: AuthConfig::default(),
            rate_limit: RateLimitConfig::default(),
            service_discovery: ServiceDiscoveryConfig::default(),
            load_balance: LoadBalanceConfig::default(),
            middleware: MiddlewareConfig::default(),
            monitoring: MonitoringConfig::default(),
            logging: LoggingConfig::default(),
        }
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 8080,
            max_connections: Some(1000),
            request_timeout: 30,
            keep_alive_timeout: 60,
            enable_https: false,
            tls: None,
        }
    }
}

impl Default for RoutingConfig {
    fn default() -> Self {
        Self {
            routes: Vec::new(),
            default_timeout: 30000,
            enable_path_rewrite: true,
            enable_request_transform: true,
        }
    }
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            providers: Vec::new(),
            jwt: None,
            api_key: None,
            basic_auth: None,
        }
    }
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            global: None,
            per_service: HashMap::new(),
            per_user: None,
            per_ip: None,
        }
    }
}

impl Default for ServiceDiscoveryConfig {
    fn default() -> Self {
        Self {
            discovery_type: "consul".to_string(),
            registry_urls: vec!["http://localhost:8500".to_string()],
            namespace: None,
            refresh_interval: 30,
            health_check_interval: 10,
            connection_timeout: 5000,
        }
    }
}

impl Default for LoadBalanceConfig {
    fn default() -> Self {
        Self {
            strategy: "round_robin".to_string(),
            health_check: HealthCheckConfig::default(),
            failover: FailoverConfig::default(),
        }
    }
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: "/health".to_string(),
            interval: 30,
            timeout: 5000,
            healthy_threshold: 2,
            unhealthy_threshold: 3,
        }
    }
}

impl Default for FailoverConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_retries: 3,
            retry_interval: 1000,
            circuit_breaker: None,
        }
    }
}

impl Default for MiddlewareConfig {
    fn default() -> Self {
        Self {
            middlewares: Vec::new(),
            enable_request_id: true,
            enable_access_log: true,
            enable_cors: false,
            cors: None,
        }
    }
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            metrics_interval: 60,
            metrics_path: "/metrics".to_string(),
            health_path: "/health".to_string(),
            prometheus: None,
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            format: "json".to_string(),
            output: vec!["stdout".to_string()],
            file: None,
        }
    }
}